package gecko;

import java.net.URI;
import java.util.Objects;

import static gecko.x.Strings.requireNotEmpty;


/**
 * @author 陈永佳 (yoojiachen@gmail.com)
 * @version 0.0.1
 */
public class Address {

    private final URI mUri;

    // protocolName :// nodeId @ domain / groupAddress / physicalAddress # tag
    Address(URI uri) {
        this.mUri = uri;
    }

    /**
     * @return 返回地址协议名称
     */
    public String protocol() {
        return mUri.getScheme();
    }

    /**
     * @return 返回节点ID
     */
    public String nodeId() {
        return mUri.getUserInfo();
    }

    /**
     * @return 返回Domain
     */
    public String domain() {
        return mUri.getHost();
    }

    /**
     * @return 返回属组地址
     */
    public String groupAddress() {
        return mUri.getPath().split("/")[0];
    }

    /**
     * @return 返回设备物理地址
     */
    public String physicalAddress() {
        return mUri.getPath().split("/")[0];
    }

    /**
     * @return 返回设备地址
     */
    public String unionAddress() {
        return mUri.getPath();
    }

    /**
     * protocolName :// nodeId @ domain / groupAddress / physicalAddress
     *
     * @param protocol        协议名称
     * @param domain          域名称
     * @param nodeId          节点ID
     * @param groupAddress    组地址
     * @param physicalAddress 物理地址
     * @return Addr对象
     */
    public static Address create(String protocol, String domain, String nodeId, String groupAddress, String physicalAddress) {
        String sb = requireNotEmpty(protocol) +
                "://" +
                requireNotEmpty(nodeId) +
                "@" +
                requireNotEmpty(domain) +
                "/" + requireNotEmpty(groupAddress) +
                "/" + requireNotEmpty(physicalAddress);
        return new Address(URI.create(sb));
    }

    ////


    @Override
    public String toString() {
        return this.mUri.toString();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Address address = (Address) o;
        return Objects.equals(mUri, address.mUri);
    }

    @Override
    public int hashCode() {
        return this.mUri.hashCode();
    }
}
